package com.lwl.mini.binding;

import com.lwl.mini.session.SqlSession;
import com.lwl.mini.util.ObjectUtils;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;

/**
 * mapper类的代理对象
 * @author lwl
 * @create 2022/4/16 9:29
 */
public class MapperProxy<T> implements InvocationHandler, Serializable {
    private final SqlSession sqlSession;
    private final Class<T> mapperInterface;
    private final Map<Method,MethodInfo> methodInfoMap;

    public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MethodInfo> methodInfoMap) {
        this.sqlSession = sqlSession;
        this.mapperInterface = mapperInterface;
        this.methodInfoMap = methodInfoMap;
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if(Object.class.equals(method.getDeclaringClass())){
            //调用Object类中定义的方法时，如toString(),直接执行
            return method.invoke(this,args);
        }
        final MethodInfo methodInfo = getMethodInfo(method);
        return methodInfo.execute(sqlSession,args);
    }

    public MethodInfo getMethodInfo(Method method){
        MethodInfo methodInfo = methodInfoMap.get(method);
        if(methodInfo == null){
            throw new BindingException("该方法未被加载进MethodInfoMap中");
        }
        return methodInfo;
    }
}
